//
//  VKStudyLeaveController.m
//  V-Learn
//
//  Created by liubo on 2019/2/12.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "VKStudyLeaveController.h"
#import "VKStudyLeaveModel.h"
#import "VKStudyLeaveCell.h"
#import "THScrollChooseView.h"
#import "LMDisposeChooseTimeView.h"

@interface VKStudyLeaveController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSString *startTime;//开始时间
@property (nonatomic, strong) NSString *endTime;//结束时间
@property (nonatomic, strong) NSString *leaveType;//请教类型
@end

@implementation VKStudyLeaveController
{
    NSString *_shangwuStr;
    NSString *_xiawuStr;
}
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"请假";
    
    NSMutableArray *sectionArray1 = [[NSMutableArray alloc]init];
    [sectionArray1 addObject:[[VKStudyLeaveModel alloc]initWithLeftLabel:@"请假类型" rightLabel:@"请选择" withType:VKStudyLeaveModelTypeLabel]];
    [self.dataArray addObject:sectionArray1];
    
    NSMutableArray *sectionArray2 = [[NSMutableArray alloc]init];
    [sectionArray2 addObject:[[VKStudyLeaveModel alloc] initWithLeftLabel:@"开始时间" rightLabel:@"请选择" withType:VKStudyLeaveModelTypeLabel] ];
    [sectionArray2 addObject:[[VKStudyLeaveModel alloc] initWithLeftLabel:@"结束时间" rightLabel:@"请选择" withType:VKStudyLeaveModelTypeLabel]];
//    [sectionArray2 addObject:[[VKStudyLeaveModel alloc] initWithLeftLabel:@"时长" rightLabel:@"请选择" withType:VKStudyLeaveModelTypeTextField]];
    [self.dataArray addObject:sectionArray2];
    
    NSMutableArray *sectionArray3 = [[NSMutableArray alloc]init];
    [sectionArray3 addObject:[[VKStudyLeaveModel alloc] initWithLeftLabel:@"请假事由" rightLabel:@"请选择" withType:VKStudyLeaveModelTypeTextField]];
    [self.dataArray addObject:sectionArray3];
    
    [self tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
}


-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, LBNAVBAR_HEIGHT, [UIScreen cz_screenWidth], [UIScreen cz_screenHeight] - LBNAVBAR_HEIGHT) style:UITableViewStyleGrouped];
        _tableView.tableFooterView = [UIView new];
        _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen cz_screenWidth], 0.01)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        _tableView.backgroundColor = [UIColor cz_colorWithRed:244 green:244 blue:244];
        
    }
    return _tableView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataArray[section]count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        return 170;
    }
    return 60;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen cz_screenWidth], 12)];
    view.backgroundColor = [UIColor cz_colorWithRed:244 green:244 blue:244];
    
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 12;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 2) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen cz_screenWidth], 150)];
        
        view.backgroundColor = [UIColor cz_colorWithRed:244 green:244 blue:244];
        UIButton *commitBtn = [[UIButton alloc]init];
        [view addSubview:commitBtn];
        [commitBtn setImage:[UIImage imageNamed:@"vkbtn"] forState:UIControlStateNormal];
        [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view).offset(40);
            make.left.equalTo(@15);
            make.width.equalTo(@([UIScreen cz_screenWidth] - 30));
            make.height.equalTo(@55);
        }];
        commitBtn.imageView.contentMode = UIViewContentModeScaleToFill;
        [commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *commitLabel = [[UILabel alloc]init];
        [view addSubview:commitLabel];
        commitLabel.textColor = [UIColor whiteColor];
        commitLabel.font = [UIFont systemFontOfSize:18];
        commitLabel.text = @"提交";
        [commitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(commitBtn).offset(15);
            make.centerX.equalTo(commitBtn);
        }];
        return view;
    }
    
    return [UIView new];
}
- (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"oneDay : %@, anotherDay : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //在指定时间前面 过了指定时间 过期
        NSLog(@"oneDay  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //没过指定时间 没过期
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //刚好时间一样.
    //NSLog(@"Both dates are the same");
    return 0;
    
}
// 提交
- (void)commitBtnClick{
    
    UITextView *textView = [self.view viewWithTag:6666];
    // 请假事由
    NSString *textViewStr = [textView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    // 时长
//    NSString *textFieldStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
//
    NSString *token = [UserModel getUserModel].token;
    NSString *startType;
    if ([self.startTime containsString:@"上午"]) {
        _shangwuStr = @"上午";
        startType = @"1";
        if ([self.endTime isEqualToString:self.startTime]) {
            [MBProgressHUD showSuccess:@"请选择正确的打卡时间" toView:self.view];
            return;
        }
    }else if([self.startTime containsString:@"下午"]){
        startType = @"2";
        _shangwuStr = @"下午";
    }
    NSString *endType;
    if ([self.endTime containsString:@"上午"]) {
        _xiawuStr = @"上午";
        endType = @"1";
    }else if([self.endTime containsString:@"下午"]){
        _xiawuStr = @"下午";
        endType = @"2";
        if ([self.endTime isEqualToString:self.startTime]) {
            [MBProgressHUD showSuccess:@"请选择正确的打卡时间" toView:self.view];
            return;
        }
    }

    NSString *startT= [self.startTime substringToIndex:10];
    NSString *endT = [self.endTime substringToIndex:10];
    
    NSString *strUrl1 = [startT stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
    NSString *startTime = [strUrl1 stringByReplacingOccurrencesOfString:@"月" withString:@"-"];
    
    
    NSString *endt = [endT stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
    NSString *endTime = [endt stringByReplacingOccurrencesOfString:@"月" withString:@"-"];

    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //下面以 '2017-04-24 08:57:29'为例代表服务器返回的时间字符串
    NSDate *date = [dateFormatter dateFromString:startTime];
    
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
    [dateFormatter2 setDateFormat:@"yyyy-MM-dd"];
    //下面以 '2017-04-24 08:57:29'为例代表服务器返回的时间字符串
    NSDate *date2 = [dateFormatter2 dateFromString:endTime];
    
    int dateIndex = [self compareOneDay:date withAnotherDay:date2];
    
    if (dateIndex==0) {
        if ([_shangwuStr isEqualToString:@"下午"]&&[_xiawuStr isEqualToString:@"上午"]) {
            [MBProgressHUD showSuccess:@"请选择正确的请假日期" toView:self.view];
            return;
        }
    }
    //请假类型
    NSInteger jiaType;
    if ([self.leaveType isEqualToString:@"事假"]) {
        jiaType = 1;
    }else if ([self.leaveType isEqualToString:@"病假"]){
        jiaType = 2;
    }else if ([self.leaveType isEqualToString:@"产假"]){
        jiaType = 3;
    }else{
        jiaType = 4;
    }
    if (self.leaveType.length ==0||self.leaveType==nil) {
        [MBProgressHUD showSuccess:@"请选择请假类型" toView:self.view];
        return;
    }
    if (startTime.length ==0) {
        [MBProgressHUD showSuccess:@"请选择开始时间" toView:self.view];
        return;
    }
    if (endTime.length ==0) {
        [MBProgressHUD showSuccess:@"请选择结束时间" toView:self.view];
        return;
    }

    if (textViewStr.length == 0||textViewStr==nil) {
        [MBProgressHUD showSuccess:@"请输入请假事由" toView:self.view];
        return;
    }
    if (dateIndex==1) {
        [MBProgressHUD showSuccess:@"请选择正确的请假日期" toView:self.view];
        return;
    }
    

    
//    NSInteger leaveDuration2 = [leaveDuration integerValue];
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setObject:token forKey:@"token"];//
    [data setObject:textView.text forKey:@"leaveInfo"];//请假事由
    [data setObject:startTime forKey:@"startDate"];//请假开始日期
    [data setObject:endType forKey:@"startType"];//请假开始时间 1上午 2下午
    [data setObject:endTime forKey:@"endDate"];//结束时间
    [data setObject:endType forKey:@"endType"];// 结束时间 1上午 2下午
//    [data setObject:@(leaveDuration2) forKey:@"leaveDuration"];//请假时长
    [data setObject:@(jiaType) forKey:@"leaveType"];//请假类型 1 事假 2 病假 3 其他
    __weak typeof(self)weakSelf = self;
    [WYHXNetWorkManager post:WKComitAskLeaveMsg_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
//        NSLog(@"%@%@",responseObj,error);
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
            [MBProgressHUD showSuccess:@"" toView:self.view];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 2) {
        //        return [UIScreen cz_screenHeight] - LBNAVBAR_HEIGHT - 336 - 110;
        return 150;
    }
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    VKStudyLeaveModel *model = self.dataArray[indexPath.section][indexPath.row];
    model.indexPath = indexPath;
    VKStudyLeaveCell *cell = [VKStudyLeaveCell cellWithTableView:tableView withModel:model withIndexPath:(NSIndexPath *)indexPath];
    cell.model = model;
    
    if (indexPath.section == 0) {
        // tag: 0
        cell.contentBtn.tag = indexPath.row + indexPath.section;
        [cell.contentBtn addTarget:self action:@selector(contentBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    if (indexPath.section == 1) {
        if (indexPath.row == 0 || indexPath.row == 1) {
            // tag: 1 2
            cell.contentBtn.tag = indexPath.row + indexPath.section;
            [cell.contentBtn addTarget:self action:@selector(contentBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        }
        if (indexPath.row==2) {
            
        }
    }
    
    return cell;
}
- (void)contentBtnClick:(UIButton *)sender{
//    NSLog(@"sender:%ld",sender.tag);
    
    NSInteger index = sender.tag;
//    NSLog(@"%ld",index);
    UIButton *btn = (UIButton *)[self.view viewWithTag:sender.tag];
    __weak typeof(self)weakSelf = self;
    // 请假类型
    if (sender.tag == 0) {
        NSArray *questionArray = @[@"事假",@"病假",@"产假",@"其他"];
        THScrollChooseView *scrollChooseView = [[THScrollChooseView alloc] initWithQuestionArray:questionArray withDefaultDesc:@"事假" with:@"请假类型"];
        [scrollChooseView showView];
        scrollChooseView.confirmBlock = ^(NSInteger index) {
//            NSLog(@"selectedQuestion:%ld",index);
            //            if (index==3) {//阻断如果没有选择
            //                return;
            //            }
            weakSelf.leaveType = questionArray[index];
            [sender setTitle:questionArray[index] forState:UIControlStateNormal];
        };
        
    }else if (sender.tag == 1){// 开始时间
        
        LMDisposeChooseTimeView *chooseTimeView = [[LMDisposeChooseTimeView alloc] initWithFrame:self.view.bounds];
        [chooseTimeView showInView:self.view];
        chooseTimeView.chooseDateWithTimerBlock = ^(NSString *dateWithTimerStr) {
//            NSLog(@"dateWithTimerStr  %@",dateWithTimerStr);
            weakSelf.startTime = dateWithTimerStr;
            [sender setTitle:dateWithTimerStr forState:UIControlStateNormal];
        };
    }else if (sender.tag == 2){// 结束时间
        LMDisposeChooseTimeView *chooseTimeView = [[LMDisposeChooseTimeView alloc] initWithFrame:self.view.bounds];
        [chooseTimeView showInView:self.view];
        chooseTimeView.chooseDateWithTimerBlock = ^(NSString *dateWithTimerStr) {
//            NSLog(@"dateWithTimerStr  %@",dateWithTimerStr);
            [sender setTitle:dateWithTimerStr forState:UIControlStateNormal];
            weakSelf.endTime = dateWithTimerStr;
        };
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}


@end
